package com.x.erp.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import com.x.erp.model.Car;
import com.x.erp.model.GateCar;
import com.x.erp.rpc.CarRpcService;
import com.x.erp.rpc.GateCarRpcService;
import com.x.erp.util.ConstantState;
import com.x.framework.controller.BaseController;
import com.x.framework.controller.ResultCode;
import com.x.framework.controller.ResultModel;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * 道闸出入车辆信息
 */
@RestController
@RequestMapping("/gate")
public class GateCarController extends BaseController {

	@Reference
	private GateCarRpcService gateCarRpcService;// 道闸出入车辆信息服务

	@Autowired
	private FastFileStorageClient fdfsClient;// 文件服务

	@Reference
	private CarRpcService carRpcService;// 车辆信息服务

	/**
	 * 查询道闸出入车辆信息
	 *
	 * @param
	 * @return
	 */
	@RequestMapping(value = "/getGateCarList", method = { RequestMethod.POST, RequestMethod.GET })
	public ResultModel getGateCarList(GateCar gateCar) {
		if(gateCar.getEndTime() != null){
			gateCar.setEndTime(this.getDate(gateCar.getEndTime(),1));
		}
		return new ResultModel(ResultCode.RESULT_SUCCESS, "查询成功", gateCarRpcService.selectGateCarList(gateCar));
	}

	/**
	 * 查询道闸出入车辆信息数量
	 *
	 * @param
	 * @return
	 */
	@RequestMapping(value = "/getGateCarNum", method = { RequestMethod.POST, RequestMethod.GET })
	public ResultModel getGateCarNum(GateCar gateCar) {
		if(gateCar.getEndTime() != null){
			gateCar.setEndTime(this.getDate(gateCar.getEndTime(),1));
		}
		Map<String, Object> res = new HashMap<>();
		res.put("total", gateCarRpcService.selectGateCarNum(gateCar));
		return new ResultModel(ResultCode.RESULT_SUCCESS, "查询成功", res);
	}

	/**
	 * 新增道闸出入车辆信息信息
	 *
	 * @param
	 * @return
	 */
	@RequestMapping(value = "/insertGateCar", method = { RequestMethod.POST, RequestMethod.GET })
	public ResultModel insertGateCar(GateCar gateCar,
	                                 @RequestParam(value = "carImageFile", required = true) CommonsMultipartFile carImageFile) {
		if (gateCar == null) {
			return new ResultModel(ResultCode.RESULT_FAIL, "道闸出入车辆信息不能为空！");
		}
		if (StringUtils.isEmpty(gateCar.getGateCode())) {
			return new ResultModel(ResultCode.RESULT_FAIL, "道闸编号不能为空！");
		}
		if (gateCar.getCarState() == null) {
			return new ResultModel(ResultCode.RESULT_FAIL, "车辆状态不能为空！");
		}
		if (gateCar.getCarState() != 1 && gateCar.getCarState() != 2) {
			return new ResultModel(ResultCode.RESULT_FAIL, "车辆状态错误！");
		}
		if (StringUtils.isEmpty(gateCar.getMarketId())) {
			return new ResultModel(ResultCode.RESULT_FAIL, "市场ID不能为空！");
		}
		if (carImageFile == null || carImageFile.isEmpty()) {
			return new ResultModel(ResultCode.RESULT_FAIL, "车辆图片不能为空");
		}
		if (!carImageFile.getContentType().contains("png") && !carImageFile.getContentType().contains("jpeg")
				&& !carImageFile.getContentType().contains("jpg")) {
			return new ResultModel(ResultCode.RESULT_FAIL, "车辆图片类型错误");
		}
		if (carImageFile.getSize() > 256 * 1024) {
			return new ResultModel(ResultCode.RESULT_FAIL, "车辆图片超出大小限制，（最大256K）");
		}
		gateCar.setCarCreateTime(new Date());
		try {
			String fileExt = StringUtils.isNotEmpty(fdfsClient.getFileExt(carImageFile.getOriginalFilename()))
					? fdfsClient.getFileExt(carImageFile.getOriginalFilename()) : "jpg";
			String pathUrl = fdfsClient.uploadFile(carImageFile.getInputStream(), fileExt);
			logger.info("pathUrl=" + pathUrl);
			if (StringUtils.isNotEmpty(pathUrl) && !pathUrl.equalsIgnoreCase("null")) {
				gateCar.setCarImage(pathUrl);
				gateCar = gateCarRpcService.insertGateCar(gateCar);
			}
		} catch (IOException e) {
			e.printStackTrace();
			return new ResultModel(ResultCode.RESULT_FAIL, "插入失败！");
		}
		return new ResultModel(ResultCode.RESULT_SUCCESS, "插入成功！", gateCar);
	}

	/**
	 * 根据RFID查询车辆是否允许出库
	 *
	 * @param carRfid
	 * @return
	 */
	@RequestMapping(value = "/getCarStateByRfid", method = { RequestMethod.POST, RequestMethod.GET })
	public ResultModel getCarStateByRfid(String carRfid, String marketId) {
		logger.info("-----------------根据RFID查询车辆是否允许出库 in-----------------");
		if (StringUtils.isEmpty(marketId)) {
			return new ResultModel(ResultCode.RESULT_FAIL, "市场ID不能为空！");
		}
		if (StringUtils.isEmpty(carRfid)) {
			return new ResultModel(ResultCode.RESULT_FAIL, "RFID不能为空！");
		}
		Car car = new Car();
		car.setCarRfid(carRfid);
		Car selectCar = carRpcService.selectCar(car);

		// Car car = new Car();
		// car.setCarRfid(carRfid);
		// car.setMarketId(marketId);
		// List<Car> cars = carRpcService.selectCarList(car);
		// if(cars != null && cars.size() > 0){
		// car = cars.get(0);
		// }else{
		// return new ResultModel(ResultCode.RESULT_FAIL, "RFID错误！");
		// }
		Map<String, Object> res = new HashMap<>();
		// if(car.getCarStockState() == ConstantState.CAR_STOCK_STATE_40){
		res.put("outGateState", true);
		res.put("message", "允许出库！");
		// }else{
		// res.put("outGateState", false);
		// res.put("message", "当前车辆状态为：" +
		// ConstantState.getCarStockStateMsg(car.getCarStockState()) +
		// "不允许出库！");
		// }
		if (selectCar != null && selectCar.getCarPledgeState() == ConstantState.CAR_PLEDG_STATE_PLEDGED
				&& selectCar.getCarSiteState() != null) {
			if (selectCar.getCarSiteState() == ConstantState.CAR_SITE_STATE_IN_FINISH) {
				res.put("outGateState", false);
				res.put("message", "该抵押车辆未提交出场申请！不允许出场！");
				return new ResultModel(ResultCode.RESULT_FAIL, res);
			}
			if (selectCar.getCarSiteState() == ConstantState.CAR_SITE_STATE_OUT_ING) {
				res.put("outGateState", false);
				res.put("message", "该抵押车辆提交的出场申请未审核！不允许出场！");
				return new ResultModel(ResultCode.RESULT_FAIL, res);
			}
		}
		logger.info("-----------------根据RFID查询车辆是否允许出库 ok-----------------");
		return new ResultModel(ResultCode.RESULT_SUCCESS, "查询成功", res);
	}
}
